<?php
/**
 * DownGoods.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/27- 下午5:40
 */

namespace common\jobs\sync;


use common\components\api\isv\Goods;
use common\exception\JobException;
use common\helpers\SendTaskHelper;
use common\dao\PddSyncLogDao;
use GuzzleHttp\Exception\GuzzleException;
use common\exception\ServiceException;
use common\models\es\dataProvider\tbMallProducts\ListMallProduct;
use common\models\PddMallProduct;
use yii\helpers\ArrayHelper;
use common\drivers\queue\Manager;
use Yii;
use common\helpers\JobHelper;
use yii\base\Exception;

class SyncGoodsToLocal extends SyncBase implements \common\drivers\interfaces\JobInterface
{
    public $args = [];


    /**
     * 同步每页请求条数
     * @var int
     */
    public $limit = 100;

    /**
     * 获取异步任务执行需要的参数
     * SyncProduct constructor.
     * @param array $args
     */
    public function __construct(array $args = [])
    {
        $this->args = $args;
        $this->totalCacheKey .= $this->args['log_id'];
    }


    /**
     * 处理队列
     * @return mixed|void
     */
    public function handle() :void
    {
        try {

            $items = new Goods();

            $syncLogDao = new PddSyncLogDao();
            $lastSyncLog = $syncLogDao->getInfoByPk($this->args['log_id']);
            $sync_type = $lastSyncLog->sync_type;
            $ids = $lastSyncLog->ids;
            //同步在售商品
            $totalLogNum = $this->syncOnsale($items, $sync_type, $ids);
            //同步下架商品
            $totalLogNum += $this->syncInventory($items, $sync_type, $ids);

            Yii::$app->redis->setex($this->totalCacheKey, 86400, $totalLogNum);

        } catch (ServiceException $e) {
            throw new JobException($e->getMessage());
        } catch (Exception $e) {
            throw new JobException($e->getMessage());
        } catch (GuzzleException $e) {
            throw new JobException($e->getMessage());
        }
    }

    /**
     * 库存商品同步
     * @param Goods $goods
     * @return int
     * @throws Exception
     * @throws GuzzleException
     * @throws ServiceException
     * @throws TaskException
     */
    private function syncInventory(Goods $goods, int $sync_type = 2, $ids)
    {
        //库存商品同步
        $priInventoryRequest = [
            'page' => 1,
            'page_size' => $this->limit,
            'is_onsale' => 0 //上下架状态，0-下架，1-上架
        ];
        $totalInventory = 0;
        do {
            $inventoryList = $goods->pddGoodsListGet($priInventoryRequest, $this->args['mall_id']);
            if (isset($inventoryList['goods_list']) && count($inventoryList['goods_list'])) {
                foreach ($inventoryList['goods_list'] as $k => $product) {
                    $args = array(
                        'uid' => $this->args['uid'],
                        'mall_id' => $this->args['mall_id'],
                        'goods_ids' => $product['goods_id']
                    );
                    if ($sync_type == 1) {
                        //全量同步
//                        SendTaskHelper::toSend([
//                            'taskName' => 'SyncProductDetail',
//                            'args' => [
//                                'goods_id' => $product['goods_id'],
//                                'uid' => $this->args['uid'] ?? 0,
//                                'log_id' => $this->args['log_id'] ?? 0,
//                                'mall_id' => $this->args['mall_id'],
//                            ]
//                        ]);
                        //写入队列
                        $spider = new SyncGoodsToDetail([
                            'goods_id' => $product['goods_id'],
                            'uid' => $this->args['uid'] ?? 0,
                            'log_id' => $this->args['log_id'] ?? 0,
                            'mall_id' => $this->args['mall_id'],
                        ]);
                        Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                        if ($inventoryList['total_count']) $totalInventory = $inventoryList['total_count'];
                    } else if ($sync_type == 3) {
                        //增量同步
                        $info = PddMallProduct::find()->select(['goods_id', 'sync_at'])
                            ->where(['goods_id' => $product['goods_id']])
                            ->one();
                        if (!$info) {
                            $totalInventory++;
//                            SendTaskHelper::toSend([
//                                'taskName' => 'SyncProductDetail',
//                                'args' => [
//                                    'goods_id' => $product['goods_id'],
//                                    'uid' => $this->args['uid'] ?? 0,
//                                    'log_id' => $this->args['log_id'] ?? 0,
//                                    'mall_id' => $this->args['mall_id'],
//                                ]
//                            ]);

                            $spider = new SyncGoodsToDetail([
                                'goods_id' => $product['goods_id'],
                                'uid' => $this->args['uid'] ?? 0,
                                'log_id' => $this->args['log_id'] ?? 0,
                                'mall_id' => $this->args['mall_id'],
                            ]);
                            Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
//                            JobHelper::toSyncDetail([
//                                'goods_id' => $product['goods_id'],
//                                'uid' => $this->args['uid'] ?? 0,
//                                'log_id' => $this->args['log_id'] ?? 0,
//                                'mall_id' => $this->args['mall_id'],
//                            ]);
                        }
                    } else if ($sync_type == 4) {
                        //同步1天内的数据
                        $info = PddMallProduct::find()->select(['goods_id', 'sync_at'])
                            ->where(['goods_id' => $product['goods_id']])
                            ->andWhere(['>', 'sync_at', time() - 86400])
                            ->one();
                        if ($info) {
                            $totalInventory++;
//                            SendTaskHelper::toSend([
//                                'taskName' => 'SyncProductDetail',
//                                'args' => [
//                                    'goods_id' => $product['goods_id'],
//                                    'uid' => $this->args['uid'] ?? 0,
//                                    'log_id' => $this->args['log_id'] ?? 0,
//                                    'mall_id' => $this->args['mall_id'],
//                                ]
//                            ]);
                            $spider = new SyncGoodsToDetail([
                                'goods_id' => $product['goods_id'],
                                'uid' => $this->args['uid'] ?? 0,
                                'log_id' => $this->args['log_id'] ?? 0,
                                'mall_id' => $this->args['mall_id'],
                            ]);
                            Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                        }
                    } else if ($sync_type == 7) {
                        //同步1天内的数据
                        $info = PddMallProduct::find()->select(['goods_id', 'sync_at'])
                            ->where(['goods_id' => $product['goods_id']])
                            ->andWhere(['>', 'sync_at', time() - 86400 * 7])
                            ->one();
                        if ($info) {
                            $totalInventory++;
//                            SendTaskHelper::toSend([
//                                'taskName' => 'SyncProductDetail',
//                                'args' => [
//                                    'goods_id' => $product['goods_id'],
//                                    'uid' => $this->args['uid'] ?? 0,
//                                    'log_id' => $this->args['log_id'] ?? 0,
//                                    'mall_id' => $this->args['mall_id'],
//                                ]
//                            ]);
                            $spider = new SyncGoodsToDetail([
                                'goods_id' => $product['goods_id'],
                                'uid' => $this->args['uid'] ?? 0,
                                'log_id' => $this->args['log_id'] ?? 0,
                                'mall_id' => $this->args['mall_id'],
                            ]);
                            Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                        }
                    } else if ($sync_type == 8) {
                        //同步指定id的数据
                        if ($ids) {
                            $idsArr = explode(',', $ids);
                            if ($idsArr) {
                                if (in_array($product['goods_id'], $idsArr)) {
                                    $totalInventory++;
                                    $spider = new SyncGoodsToDetail([
                                        'goods_id' => $product['goods_id'],
                                        'uid' => $this->args['uid'] ?? 0,
                                        'log_id' => $this->args['log_id'] ?? 0,
                                        'mall_id' => $this->args['mall_id'],
                                    ]);
                                    Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                                }
                            }
                        }
                    }
                }
                $priInventoryRequest['page'] += 1;
            } else {
                break;
            }
        } while (count($inventoryList['goods_list']) >= $priInventoryRequest['page_size']);
        return $totalInventory;
    }



    /**
     * 同步在售商品
     * @param Goods $goods
     * @return int
     * @throws Exception
     * @throws GuzzleException
     * @throws ServiceException
     * @throws TaskException
     */
    private function syncOnsale(Goods $goods, int $sync_type = 2, $ids = '')
    {
        //在售商品同步
        $priRequest = [
            'page' => 1,
            'page_size' => $this->limit,
            'is_onsale' => 1 //上下架状态，0-下架，1-上架
        ];

        $totalOnsale = 0;
        do {
            $productList = $goods->pddGoodsListGet($priRequest, $this->args['mall_id']);
            if (isset($productList['goods_list']) && count($productList['goods_list'])) {

                foreach ($productList['goods_list'] as $k => $product) {
                    $args = array(
                        'uid' => $this->args['uid'],
                        'mall_id' => $this->args['mall_id'],
                        'goods_ids' => $product['goods_id']
                    );
                    if ($sync_type == 1) {
                        //全量同步
                        $spider = new SyncGoodsToDetail([
                            'goods_id' => $product['goods_id'],
                            'uid' => $this->args['uid'] ?? 0,
                            'log_id' => $this->args['log_id'] ?? 0,
                            'mall_id' => $this->args['mall_id'],
                        ]);
                        Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                        if ($productList['total_count']) $totalOnsale = $productList['total_count'];
                    } else if ($sync_type == 3) {
                        //增量同步
                        $info = PddMallProduct::find()->select(['goods_id', 'sync_at'])
                            ->where(['goods_id' => $product['goods_id']])
                            ->one();
                        if (!$info) {
                            $spider = new SyncGoodsToDetail([
                                'goods_id' => $product['goods_id'],
                                'uid' => $this->args['uid'] ?? 0,
                                'log_id' => $this->args['log_id'] ?? 0,
                                'mall_id' => $this->args['mall_id'],
                            ]);
                            Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                            $totalOnsale++;
                        }
                    } else if ($sync_type == 4) {
                        //同步1天内的数据
                        $info = PddMallProduct::find()->select(['goods_id', 'sync_at'])
                            ->where(['goods_id' => $product['goods_id']])
                            ->andWhere(['>', 'sync_at', time() - 86400])
                            ->one();
                        if ($info) {
                            $totalOnsale++;
                            $spider = new SyncGoodsToDetail([
                                'goods_id' => $product['goods_id'],
                                'uid' => $this->args['uid'] ?? 0,
                                'log_id' => $this->args['log_id'] ?? 0,
                                'mall_id' => $this->args['mall_id'],
                            ]);
                            Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                        }
                    } else if ($sync_type == 7) {
                        //同步1天内的数据
                        $info = PddMallProduct::find()->select(['goods_id', 'sync_at'])
                            ->where(['goods_id' => $product['goods_id']])
                            ->andWhere(['>', 'sync_at', time() - 86400 * 7])
                            ->one();
                        if ($info) {
                            $totalOnsale++;
                            $spider = new SyncGoodsToDetail([
                                'goods_id' => $product['goods_id'],
                                'uid' => $this->args['uid'] ?? 0,
                                'log_id' => $this->args['log_id'] ?? 0,
                                'mall_id' => $this->args['mall_id'],
                            ]);
                            Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                        }
                    } else if ($sync_type == 8) {
                        //同步指定id的数据
                        if ($ids) {
                            $idsArr = explode(',', $ids);
                            if ($idsArr) {
                                if (in_array($product['goods_id'], $idsArr)) {
                                    $totalOnsale++;
                                    $spider = new SyncGoodsToDetail([
                                        'goods_id' => $product['goods_id'],
                                        'uid' => $this->args['uid'] ?? 0,
                                        'log_id' => $this->args['log_id'] ?? 0,
                                        'mall_id' => $this->args['mall_id'],
                                    ]);
                                    Manager::factory(Yii::$app->params['queue']['syncDetail'])->push($spider);
                                }
                            }
                        }
                    }

                }
                $priRequest['page'] += 1;
            } else {
                break;
            }
        } while (count($productList['goods_list']) >= $priRequest['page_size']);
        return $totalOnsale;
    }
}